import 'package:flutter/material.dart';
import 'package:flutter_business_2003a/bean/category_parent_bean_result.dart';
import 'package:flutter_business_2003a/bean/categoty_goods_list_bean_result.dart';
import 'package:flutter_business_2003a/provider/child_category_provider.dart';
import 'package:flutter_business_2003a/provider/detail_info_provider.dart';
import 'package:flutter_business_2003a/router/application.dart';
import 'package:flutter_business_2003a/service/service_method.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:provider/provider.dart';

class CategoryPage extends StatefulWidget {
  const CategoryPage({Key? key}) : super(key: key);

  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  List<CategoryParentBean?>? parentList = [];

  // List<CategoryChildtBean?>? childList = [];
  bool isFirst = true;

  //请求一级列表的方法
  Future _getCategoryParent() async {
    await request('categoryParent', null).then((value) {
      parentList = CategoryParentBeanResult.fromJson(value).data;
    });
    if (isFirst) {
      Provider.of<ChildCategoryProvider>(context, listen: false)
          .setChildCategory(parentList![0]!.data);
      isFirst = false;
      _getCategoryGoodsList(14, 1, 10, context);
    }

    return parentList;
  }

  //请求三级列表的方法
  void _getCategoryGoodsList(id, page, size, context) async {
    var formData = {'category_id': id, 'currentPage': page, 'pageSize': size};
    await request('categoryGoodsList', formData).then((value) {
      Provider.of<ChildCategoryProvider>(context, listen: false)
          .setCategoryGoodsList(
              CategoryGoodsListBeanResult.fromJson(value).data);
      // print(value);
    });
  }

  //一级列表的item
  Widget _leftInkWell(index) {
    bool isClick = false;
    isClick = (index == Provider.of<ChildCategoryProvider>(context).parentIndex)
        ? true
        : false;
    return InkWell(
      onTap: () {
        // childList = parentList![index]!.data;
        Provider.of<ChildCategoryProvider>(context, listen: false)
            .setChildCategory(parentList![index]!.data);
        Provider.of<ChildCategoryProvider>(context, listen: false)
            .changeParentIndex(index);
        Provider.of<ChildCategoryProvider>(context, listen: false)
            .changeChildIndex(0);
        _getCategoryGoodsList(parentList![index]!.data![0]!.id, 1, 10, context);
        Provider.of<ChildCategoryProvider>(context, listen: false)
            .setChildId(parentList![index]!.data![0]!.id);
        Provider.of<ChildCategoryProvider>(context, listen: false).reSize();
      },
      child: Container(
        height: ScreenUtil().setHeight(100).toDouble(),
        padding: const EdgeInsets.only(left: 20, top: 15),
        decoration: BoxDecoration(
            color: isClick ? Colors.black26 : Colors.white,
            border: const Border(
                bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Text(
          parentList![index]!.category_name!,
          style: TextStyle(fontSize: ScreenUtil().setSp(28).toDouble()),
        ),
      ),
    );
  }

  //一级分类的列表
  Widget _leftCategoryNav() {
    return Container(
      width: ScreenUtil().setWidth(180).toDouble(),
      decoration: const BoxDecoration(
          border: Border(right: BorderSide(width: 1, color: Colors.black12))),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _leftInkWell(index);
        },
        itemCount: parentList!.length,
      ),
    );
  }

  @override
  void initState() {
    // var formData = {'category_id': 14, 'currentPage': 1, 'pageSize': 10};
    // request('categoryGoodsList', formData).then((value) => print(
    //     CategoryGoodsListBeanResult.fromJson(value)
    //         .data![0]!
    //         .goodsInfoList!
    //         .length));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334); //Iphone6的尺寸基准,设计图尺寸
    return Scaffold(
      appBar: AppBar(
        title: const Text('分类'),
      ),
      body: Row(
        children: [
          FutureBuilder(
            future: _getCategoryParent(),
            builder: (context, val) {
              if (val.hasData) {
                return _leftCategoryNav();
              } else {
                return const Center(
                  child: Text('加载中'),
                );
              }
            },
          ),
          Column(
            children: const [
              RightCategoryNav(),
              Expanded(child: CategoryGoodsList())
            ],
          )
        ],
      ),
    );
  }
}

//二级分类列表
class RightCategoryNav extends StatelessWidget {
  const RightCategoryNav({Key? key}) : super(key: key);

  //请求三级列表的方法
  void _getCategoryGoodsList(id, page, size, context) async {
    var formData = {'category_id': id, 'currentPage': page, 'pageSize': size};
    await request('categoryGoodsList', formData).then((value) {
      Provider.of<ChildCategoryProvider>(context, listen: false)
          .setCategoryGoodsList(
              CategoryGoodsListBeanResult.fromJson(value).data);
      // print(value);
    });
  }

  //右侧上方小导航的item
  Widget _rightInkWell(CategoryChildtBean item, context, index) {
    bool isClick = false;
    isClick = (index == Provider.of<ChildCategoryProvider>(context).childIndex);
    return InkWell(
      onTap: () {
        Provider.of<ChildCategoryProvider>(context, listen: false)
            .changeChildIndex(index);
        _getCategoryGoodsList(
            item.id,
            1,
            Provider.of<ChildCategoryProvider>(context, listen: false).size,
            context);
        Provider.of<ChildCategoryProvider>(context, listen: false)
            .setChildId(item.id);
        Provider.of<ChildCategoryProvider>(context, listen: false).reSize();
      },
      child: Container(
        color: isClick ? Colors.pink : Colors.white,
        padding: const EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
        child: Text(
          item.category_name!,
          style: TextStyle(fontSize: ScreenUtil().setSp(28).toDouble()),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(80).toDouble(),
      width: ScreenUtil().setWidth(570).toDouble(),
      decoration: const BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _rightInkWell(
              Provider.of<ChildCategoryProvider>(context)
                  .childCategoryList[index],
              context,
              index);
        },
        itemCount: Provider.of<ChildCategoryProvider>(context)
            .childCategoryList
            .length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }
}

class CategoryGoodsList extends StatelessWidget {
  const CategoryGoodsList({Key? key}) : super(key: key);

  //请求三级列表的方法
  void _getCategoryGoodsList(id, page, size, context) async {
    var formData = {'category_id': id, 'currentPage': page, 'pageSize': size};
    await request('categoryGoodsList', formData).then((value) {
      Provider.of<ChildCategoryProvider>(context, listen: false)
          .addCategoryGoodsList(
              CategoryGoodsListBeanResult.fromJson(value).data);
    });
  }

  //商品图片
  Widget _goodsImage(index, context) {
    return SizedBox(
      width: ScreenUtil().setWidth(200).toDouble(),
      child: Image.network(Provider.of<ChildCategoryProvider>(context)
          .categoryGoodsList[index]
          .goods_default_icon!),
    );
  }

  //商品名称
  Widget _goodsName(index, context) {
    return Container(
      width: ScreenUtil().setWidth(370).toDouble(),
      padding: const EdgeInsets.all(5.0),
      child: Text(
        Provider.of<ChildCategoryProvider>(context)
            .categoryGoodsList[index]
            .goods_desc!,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28).toDouble()),
      ),
    );
  }

  //商品价格
  Widget _goodsPrice(index, context) {
    return Container(
      margin: const EdgeInsets.only(top: 20.0),
      width: ScreenUtil().setWidth(370).toDouble(),
      child: Row(
        children: [
          Text(
            '价格:¥${Provider.of<ChildCategoryProvider>(context).categoryGoodsList[index].goods_default_price}元',
            style: TextStyle(
                fontSize: ScreenUtil().setSp(23).toDouble(),
                color: Colors.pink),
          ),
          Text(
            '原价:¥${Provider.of<ChildCategoryProvider>(context).categoryGoodsList[index].goods_default_price}元',
            style: TextStyle(
                fontSize: ScreenUtil().setSp(23).toDouble(),
                color: Colors.black26,
                decoration: TextDecoration.lineThrough),
          ),
        ],
      ),
    );
  }

  //构建商品的Item
  Widget _listWidgetItem(index, context) {
    return InkWell(
      onTap: () {
        CategoryGoodsBean goodsBean =
            Provider.of<ChildCategoryProvider>(context, listen: false)
                .categoryGoodsList[index];
        Provider.of<DetailInfoProvider>(context, listen: false).setGoodsInfo(goodsBean);
        Application.router!.navigateTo(context, '/detail');
      },
      child: Container(
        padding: const EdgeInsets.only(top: 5.0, bottom: 5.0),
        decoration: const BoxDecoration(
            color: Colors.white,
            border:
                Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
        child: Row(
          children: [
            _goodsImage(index, context),
            Column(
              children: [
                _goodsName(index, context),
                _goodsPrice(index, context),
              ],
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: ScreenUtil().setWidth(570).toDouble(),
      child: EasyRefresh(
        onLoad: () async {
          _getCategoryGoodsList(
              Provider.of<ChildCategoryProvider>(context, listen: false)
                  .childId,
              1,
              Provider.of<ChildCategoryProvider>(context, listen: false).size,
              context);
          Provider.of<ChildCategoryProvider>(context, listen: false).addSize();
        },
        footer: ClassicalFooter(
            bgColor: Colors.white,
            textColor: Colors.pink,
            infoColor: Colors.pink,
            showInfo: true,
            infoText: '加载中',
            loadReadyText: '上拉加载',
            loadedText: '加载完成',
            loadingText: '正在加载',
            loadText: '上拉加载'),
        child: ListView.builder(
            itemCount: Provider.of<ChildCategoryProvider>(context)
                .categoryGoodsList
                .length,
            itemBuilder: (context, index) {
              return _listWidgetItem(index, context);
            }),
      ),
    );
  }
}
